﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace SocketServer
{
    public partial class Form1 : Form
    {
        private int port;
        private Socket mySocket;
        private Socket myAcceptSocket;

        delegate void ControlChangeHandler(string msg1, string msg2);

        public Form1()
        {
            InitializeComponent();
        }

        private void StartListen()
        {
            port = Convert.ToInt32(this.tbPort.Text.Trim());
            mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            mySocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port));
            mySocket.Listen(10);

            string msg = "等待Socket客户联机中...";

            this.Invoke(new ControlChangeHandler(this.onChange), new object[] { msg, string.Empty });
        }

        private void Accept()
        {
            byte[] data = new byte[1024];
            int length;

            string msg = "开始接受客户端的联机请求，接收联机信息......";
            this.Invoke(new ControlChangeHandler(this.onChange), new object[] { msg, "" });

            myAcceptSocket = mySocket.Accept();
            length = myAcceptSocket.Receive(data);

            msg = "接收了" + length.ToString() + "个字节的数据";
            string msg1 = Encoding.ASCII.GetString(data);
            this.Invoke(new ControlChangeHandler(this.onChange), new object[] { msg, msg1 });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(this.StartListen));
            thread.IsBackground = true;
            thread.Start();
        }

        private void onChange(string msg1, string msg2)
        {
            if (msg1 != "")
            {
                this.txtConnection.Text += msg1 + "\r\n";
            }
            if (msg2 != "")
            {
                this.txtAccept.Text += msg2 + "\r\n";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(this.Accept));
            th.IsBackground = true;
            th.Start();
        }
    }
}
